//
// Created by 67678 on 2023/3/12.
//

#include "webServer.h"
#include "event/eventLoop.h"
#include "threadPool/threadPool.h"
#include "socket/socketServer.h"
#include "socket/epoll.h"
#include "timer/timer.h"
#include "log.h"

using namespace webServer;
using namespace event;
using namespace threadPool;
using namespace socket_epoll;
using namespace timer;

WebServer::WebServer() {
    log("webServer start running!");

}

WebServer::~WebServer() {
    log("webServer end running!");
    close();
}


void WebServer::init() {
    log("webServer initiating!");

    ThreadPool &threadPool = ThreadPool::getInstance();
    threadPool.init(4);

    EventLoop &eventLoop = EventLoop::getInstance();
    eventLoop.init();
    eventLoop.loopBackground();

    Epoll &epoll = Epoll::getInstance();
    epoll.init();

    SocketServer &socketServer = SocketServer::getInstance();
    socketServer.init();

    Timer &timer = Timer::getInstance();
    timer.init();

}


void WebServer::run() {
    log("webServer start working!");

    SocketServer &socketServer = SocketServer::getInstance();

    EventLoop &eventLoop = EventLoop::getInstance();

    while (!done_)
        for (auto &event: socketServer.getEvents())
            eventLoop.addEvent(event);

}

void WebServer::close() {
    if(done_) return;
    log("webServer closing!");
    done_ = true;
}

